package com.kitty.game.activity.service.other;

import com.kitty.common.core.SchedulerManager;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.Position;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.house.HouseController;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LuoBoTaoZiHandler extends FightActivityHandler {
    Logger logger = LoggerFactory.getLogger(HouseController.class);
    @Autowired
    FightService fightService;
    private static final List<Integer> MAPIDS = Arrays.asList(6000, 11000);
    /**攻城怪物持续时间，单位毫秒*/
    private static final long PIRATE_CONTINUED_TIME = 30 * TimeUtil.ONE_MINUTE;
    /**每个地图显示的怪物数量*/
    private static final int PIRATE_COUNT_PER_MAP = 50;
    private static final int PIRATE_ICON = 6201;
    private static final String PIRATE_NAME = "桃子萝卜猎人";
    private static final String CONTENT;

    public void flushNpc() {
        /**先让之前刷新的攻城怪物消失*/
        //hidePirate();

        /**遍历刷新攻城怪物*/
        for (int mapId : MAPIDS) {
            for (int i=0; i<PIRATE_COUNT_PER_MAP; i++) {
                createPirate(mapId);
            }
        }
        (SpringUtils.getBean(ChatService.class)).sendNumor("抢夺萝卜桃子的#Y桃子萝卜猎人#n，现已登录#Z东海渔村、桃柳林#Z请各位有能力的玩家前去击杀桃子萝卜猎人，必定获得萝卜和桃子，几率获得大萝卜和大桃子，活动持续30分钟，时间到猎人就会逃跑！", "role");
        (SpringUtils.getBean(ChatService.class)).sendAdnotice("抢夺萝卜桃子的#Y桃子萝卜猎人#n，现已登录#Z东海渔村、桃柳林#Z请各位有能力的玩家前去击杀桃子萝卜猎人，必定获得萝卜和桃子，几率获得大萝卜和大桃子，活动持续30分钟，时间到猎人就会逃跑！");
        /**增加定时任务，持续时间结束后删除*/
        SchedulerManager.getInstance().schedule(() -> hidePirate(), PIRATE_CONTINUED_TIME);
    }


    /**在地图上刷新一个攻城怪物*/
    private void createPirate(int mapId) {
        Position position = getRandomPosition(mapId);

        NPC npc = new NPC();
        npc.setIcon(PIRATE_ICON);

        npc.setId(SpringUtils.getBean(NewBossService.class).getTempNpcId());
        npc.setX(position.getX());
        npc.setY(position.getY());
        npc.setFangxiang((short) new Random().nextInt(8));/**随机方向*/
        npc.setMapId(mapId);
        npc.setCreateTime(System.currentTimeMillis());
        npc.setEndTime(npc.getCreateTime() + PIRATE_CONTINUED_TIME);
        npc.setType(NPC.TYPE_LUOBOTAOZI);
        npc.setContent(CONTENT);
        npc.setName(PIRATE_NAME);
        npc.setBossSetName(PIRATE_NAME);

        bossService.broadcastNpcShow(null, npc);

        DataCache.MONSTER_NPCS.put(npc.getId(), npc);

        Set<Integer> set = DataCache.MONSTER_MAP_NPC.get(mapId);
        if (set == null) {
            set = new HashSet<>();
            DataCache.MONSTER_MAP_NPC.put(mapId, set);
        }
        DataCache.MONSTER_MAP_NPC.get(mapId).add(npc.getId());
    }

    /**使所有海盗在对应地图上消失*/
    public void hidePirate() {
        logger.warn("删除npc==萝卜桃子怪物");
        if (DataCache.MONSTER_NPCS.size() > 0) {
            List<NPC> list = new ArrayList<>(DataCache.MONSTER_NPCS.values());
            for (NPC npc : list) {
                if (npc.isInFight()) {
                    /**在战斗中隐藏*/
                    bossService.broadcastNpcHide(null, npc);
                } else {
                    clearPirate(npc);
                }
            }
        }
    }

    /**移除海盗*/
    private void clearPirate(NPC npc) {

        if (npc == null) {return ;}
        logger.debug("移除被消灭的萝卜桃子怪物=={}{}",npc.getId(),npc.getName());

        DataCache.MONSTER_NPCS.remove(npc.getId());
        Set<Integer> set1 = DataCache.MONSTER_MAP_NPC.get(npc.getMapId());
        if (set1 != null) {
            set1.remove(npc.getId());
        }
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());

        bossService.broadcastNpcHide(null, npc);
    }

    protected String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        if (bossNpc.isInFight()) {
            return "可恨的强盗，萝卜桃子也抢夺。[离开]";
        } else {
            int teamCount = this.teamService.getTeamCount(role);
            if (teamCount < 1) {
                return "你还是先组队再来向我挑战吧！[离开]";
            } else {
                Team team = this.teamService.getTeam(role.getRoleId());
                String names = this.teamService.checkMember(team, (memberRole) -> {
                    return memberRole.getLevel() < 40;
                });
                if (names != null) {
                    return MessageFormat.format("#Y{0}#n的等级还没有{1}级。[离开]", names, 40);
                } else {
                    names = this.teamService.checkMember(team, (memberRole) -> {
                        return this.getRoleRemainCount(memberRole) <= 0;
                    });
                    if (names != null) {
                        return "#R" + names + "#n没有挑战次数";
                    } else {
                        return this.getRoleRemainCount(role) <= 0 ? "#R" + role.getName() + "#n没有挑战次数" : null;
                    }
                }
            }
        }
    }

    private byte getRoleRemainCount(Role role) {
        return (byte)SpringUtils.getActivityService().getRemainCount(role, ActivityType.luobotaozi_ACTIVTY);
    }


    //检测是否有桃子任务
//    protected void doStartFight(Role role, NPC bossNpc) {
//        int hour = Calendar.getInstance().get(11);
//        int minute = Calendar.getInstance().get(12);
//        if (!role.getActivity().isLuobotaozi()) {
//            MessagePusher.pushMessage((Role)role, new RespMsg("当前没有开启萝卜桃子任务，请去天墉城千面怪开启！"));
//        } else {
//            List<BossParam> bossParamList = this.newBossParamList(role, bossNpc);
//            BossFightParam bossFightParam = new BossFightParam(bossParamList, this.getFightType(role));
//            bossFightParam.setNpcId(bossNpc.getId());
//            int maxRoleLevel = this.teamService.getMaxRoleLevelInTeam(role);
//            bossFightParam.setNpcLevel((short)maxRoleLevel);
//            this.bossService.startFightToBoss(role, bossFightParam);
//        }
//    }


     //不检测是否有桃子任务
    @Override
    public void doStartFight(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);

        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
        bossFightParam.setNpcId(bossNpc.getId());
        Fight fight = bossService.startFightToBoss(role, bossFightParam);
    }



    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList();
        int count = 10;
        BossSet bossSet = this.bossService.getBossSet(bossNpc.getBossSetName());
        bossParamList.add(new BossParam(bossSet, bossNpc.getName()));

        for(int i = 1; i < count; ++i) {
            bossSet = this.bossService.getBossSet("桃子萝卜猎人");
            bossParamList.add(new BossParam(bossSet, "桃子萝卜猎人"));
        }

        return bossParamList;
    }

//    protected int getFightType(Role role) {
//        return 78;
//    }
    @Override
    protected int getFightType(Role role) {
        return Const.luobotaozi;
    }

    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    protected void clearNpcAfterWin(Role role, NPC bossNpc) {
        this.clearNpc(bossNpc);
    }

    private void clearNpc(NPC npc) {
        if (npc != null) {
            this.bossService.delTaskNpc(npc);
            this.removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());
            this.bossService.broadcastNpcHide(null, npc);
        }
    }

    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        int count = getRoleRemainCount(role);
        if (count > 0) {/*次数在npc类 这个0只是取数*/
            if (!teamService.isInTeam(role)) {
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("离队无法获得奖励"));
                return;
            }
            // 这里改成公共获取配置 经验，道行，武学 奖励。 不再单独写
            fightService.sendBossBasicsReward(role,fightEndEvent);
            SpringUtils.getActivityService().addFinishCount(role, ActivityType.luobotaozi_ACTIVTY, 1);
            fightService.sendBossExtReward(role,fightEndEvent);


        } else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("今日挑战次数以达到上限！不会给奖励"));
            return;
        }
    }

    protected void clearNpcTimeOut(NPC npc) {
        this.clearNpc(npc);
    }

    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);
        this.teamService.memberHandleThreadLocal(role, (memberRole) -> {
            SpringUtils.getRoleService().punishFightDead(memberRole);
        });
    }

    static {
        CONTENT = "只有最勇敢的人，才可以得到萝卜桃子！\n#R战斗结束时死亡的角色会受到惩罚。#n[我要挑战/" + NpcButton.luobotaozi.getKey() + "][离开]";
    }
}
